import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
const wx = window["wx"];
import *as cc from "cc";
import SkdComm from './SkdComm';
import Util from './Util';
import DatasSpace from './Tool/DatasSpace';
import { MISSION_TYPE } from '../Cube/Levels';
import { KuaishouAdAdapter } from './KuaishouAdAdapter';

@ccclass('AdComponent')
export class AdComponent {
  //创建本类的全局调用变量
  public static _instance: AdComponent = null
  public static get Instance() {
    if (null == this._instance) {
      this._instance = new AdComponent();
    }
    return this._instance;
  }
  //激励视频广告
  VideoAd1 = null;
  //插屏广告
  interstitialAd1 = null;
  //banner广告
  bannerAd1 = null;
  customAd;
  private _callBack: Function;
  private _lasttryplaytime: number = 0;
  public timeOffset: number = 0;

  createAds() {
    console.log('初始化广告系统');
    // 优先使用快手广告系统
    if (typeof (window as any).ks !== 'undefined') {
      console.log('使用快手广告系统');
      KuaishouAdAdapter.Instance.preloadAd();
      return;
    }
    
    console.log('非快手环境，跳过广告创建');
    return;
    
    if (cc.sys.platform == SkdComm.Instance.platformType && wx.createRewardedVideoAd) {

      //=========================================激励视频广告==================================s==============
      this.VideoAd1 = wx.createRewardedVideoAd({
        adUnitId: 'adunit-4409e43d9988e0d9'
      });

      this.VideoAd1.onError((res) => {
        console.log("onError", res);
      });

      this.VideoAd1.onLoad(() => {
        console.log('广告加载成功');
      })

      this.VideoAd1.onClose(res => {
        if (res && res.isEnded || res === undefined) {
          console.log("正常播放结束，可以下发游戏奖励");
          DatasSpace.Instance.addMission_Target(MISSION_TYPE.VIDEO_COUNT, 1)
          DatasSpace.Instance.addLongMission_Target(MISSION_TYPE.VIDEO_COUNT, 1)

          this._callBack(true);
        }
        else {
          console.log("播放中途退出，不下发游戏奖励");
          this._callBack(false);
        }
      })


      //=========================================插屏广告==================================================

      // 创建插屏广告实例，提前初始化
      if (wx.createInterstitialAd) {
        this.interstitialAd1 = wx.createInterstitialAd({
          adUnitId: 'adunit-437a3494ab8daa21'
        });

        this.interstitialAd1.onError((res) => {
          console.log("插屏onError", res);
        });

        this.interstitialAd1.onClose(() => {
          console.log('插屏关闭');
          this.interstitialAd1.destroy();
        });
      }

      //=========================================Banner广告==================================================
      //获取屏幕高度和宽度
      let this_phone_Height = wx.getSystemInfoSync().windowHeight;
      let this_phone_Width = wx.getSystemInfoSync().windowWidth;

      if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
        //  创建 Banner 广告实例，提前初始化
        this.bannerAd1 = wx.createBannerAd({
          adUnitId: 'adunit-8db7047173794bef',
          adIntervals: 30,
          style: {
            left: 0,
            top: 0,
            width: 20,
          }
        });

        this.bannerAd1.onError(err => {
          console.log(err)
        });

        this.bannerAd1.onLoad(() => {
          console.log("Banner广告加载成功");
        });


        this.bannerAd1.onResize(res => {
          this.bannerAd1.style.top = (this_phone_Height - this.bannerAd1.style.realHeight) - 3;
          this.bannerAd1.style.left = (this_phone_Width - this.bannerAd1.style.realWidth) / 2;
        });
      }

      this.customAd = wx.createCustomAd({
        adUnitId: 'adunit-b4a0aba16c9b0f18',
        adIntervals: 31,
        style: {
          left: 0,
          top: 0,
          width: this_phone_Width,// 用于设置组件宽度，只有部分模板才支持，如矩阵格子模板
          fixed: 70 // fixed 只适用于小程序环境
        }
      });

      this.customAd.onLoad(() => console.log('原生模板广告加载成功'));
      this.customAd.onError(err => console.log(err));


    }
  }

  showBannerAd() {
    console.log('Banner广告已禁用');
    return;
    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
      this.customAd.show();
      this.bannerAd1.show();
    }
  }

  showCoustomAd() {
    console.log('原生模板广告已禁用');
    return;
    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
      this.customAd.show();
    }

  }

  hideBannerAd() {
    console.log('隐藏Banner广告已禁用');
    return;
    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
      this.customAd.hide();
      this.bannerAd1.hide();
    }
  }

  hideCoustomAd() {
    console.log('隐藏原生模板广告已禁用');
    return;
    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
      this.customAd.hide();
    }

  }

  showInterstitialFullShow() {
    console.log('插屏广告已禁用');
    return;
    // if (Util.Instance.isShowInster == false) {
    //   return;
    // }
    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
      if (this.interstitialAd1) {

        this.interstitialAd1.show().catch((err) => {
          this.interstitialAd1 = wx.createInterstitialAd({
            adUnitId: 'adunit-437a3494ab8daa21',
          });
          this.interstitialAd1.show();
          console.log(err);
        });
        // Util.Instance.isShowInster = false;
        // Util.Instance.insterAdCountDown();
      }
    }
  }

  /**自动显示插屏广告 每隔1分钟 */
  autoShowInsterAd() {
    console.log('自动插屏广告已禁用');
    return;
    if (Util.Instance.isShowInster == false) {
      return;
    }
    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && wx.createRewardedVideoAd) {
      this.interstitialAd1.show().catch((err) => {
        this.interstitialAd1 = wx.createInterstitialAd({
          adUnitId: 'adunit-437a3494ab8daa21',
        });
        this.interstitialAd1.show();

        console.log(err);
      });
      Util.Instance.isShowInster = false;
      Util.Instance.insterAdCountDown();
    }
  }

  public loadVideoAd(type: number, callback: Function) {
    // 检查是否为快手环境
    if (typeof (window as any).ks !== 'undefined') {
      console.log('使用快手激励视频广告');
      KuaishouAdAdapter.Instance.showRewardedVideoAd((success: boolean) => {
        if (success) {
          // 添加任务奖励
          DatasSpace.Instance.addMission_Target(MISSION_TYPE.VIDEO_COUNT, 1);
          DatasSpace.Instance.addLongMission_Target(MISSION_TYPE.VIDEO_COUNT, 1);
        }
        callback(success);
      });
      return;
    }
    
    // 非快手环境，模拟成功
    console.log('非快手环境，模拟激励视频广告成功');
    setTimeout(() => {
      callback(true);
      DatasSpace.Instance.addMission_Target(MISSION_TYPE.VIDEO_COUNT, 1);
      DatasSpace.Instance.addLongMission_Target(MISSION_TYPE.VIDEO_COUNT, 1);
    }, 100);
    return;
    
    if (this.getServerTime() - this._lasttryplaytime < 1000) {
      //console.log("点击过于频繁")
      //UtilsTool.popTip("点击过于频繁",cc.find('Canvas'));
      console.log("点击过于频繁");
      return;
    }
    console.log("尝试播放广告")
    this._lasttryplaytime = this.getServerTime();
    this._callBack = callback;

    if (cc.sys.platform == cc.sys.Platform.WECHAT_GAME && this.VideoAd1) {
      // 用户触发广告后，显示激励视频广告
      this.VideoAd1.show().catch(() => {
        // 失败重试
        this.VideoAd1.load()
          .then(() => this.VideoAd1.show())
          .catch(err => {
            console.log('激励视频 广告显示失败');
            // MsgHints.show("暂时没有广告" + err.errCode + "/" + err.errMsg);
            this._callBack(false);
          })
      })
    }
    else {
      this._callBack(true);
      DatasSpace.Instance.addMission_Target(MISSION_TYPE.VIDEO_COUNT, 1)
      DatasSpace.Instance.addLongMission_Target(MISSION_TYPE.VIDEO_COUNT, 1)
    }

    this._callBack(false);
  }


  // public loadVideoAd(type: number, callback: Function) {
  //     this._callBack = callback;
  //     this._callBack(true);
  // }

  getServerTime() {
    return new Date().getTime() + this.timeOffset;
  }

  /**
   * 获得范围内随机数
   * 
   */
  rnd(n, m) {
    var random = Math.floor(Math.random() * (m - n + 1) + n);
    return random;
  }
}



